package com.conversationboard.formatter.custom;

import java.sql.SQLException;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import com.conversationboard.model.propertybag.Property;
import com.conversationboard.model.propertybag.PropertyBag;

public class JavascriptFormatter implements ICustomFormatter {

    private String getJavascriptCode() throws ScriptExecutionException {

        try {
            Property property = PropertyBag.get("htmlprocessor.js");

            if (property != null) {
                return property.getValue();
            }

        } catch (SQLException e) {
            throw new ScriptExecutionException(e);
        }

        return "input";
    }


    public String format(String input) throws ScriptExecutionException {

        Context context = null;

        try {
            context = Context.enter();
            Scriptable scope = context.initStandardObjects();
            Object wrappedInput = Context.javaToJS(input, scope);

            ScriptableObject.putProperty(scope, "input", wrappedInput);

            Object result = context.evaluateString(scope, this.getJavascriptCode(), "htmlprocessor.js", 1, null);

            return Context.toString(result);

        } finally {
            Context.exit();
        }

    }

}
